/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ResidencyPageFinal.java
 *
 * Created on 07 14, 12, 4:11:19 PM
 */
package Display;

import java.sql.ResultSet;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Aeron
 */
public class ResidencyPageFinal extends javax.swing.JFrame {

    /** Creates new form ResidencyPageFinal */
    public ResidencyPageFinal() {
        initComponents();
        this.setSize(325,600);
        setLocationRelativeTo(null);
    // timplahin na lang po ito. :)
        this.setSize(300,500);
        this.setBounds(100, 70, 300, 500);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        idnumberfield = new javax.swing.JTextField();
        timeIn = new javax.swing.JButton();
        timeOut = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        userlist = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        message = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(null);

        idnumberfield.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idnumberfieldActionPerformed(evt);
            }
        });
        getContentPane().add(idnumberfield);
        idnumberfield.setBounds(130, 120, 140, 30);

        timeIn.setFont(new java.awt.Font("Garamond", 0, 14)); // NOI18N
        timeIn.setText("Time In");
        timeIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                timeInActionPerformed(evt);
            }
        });
        getContentPane().add(timeIn);
        timeIn.setBounds(50, 160, 90, 40);

        timeOut.setFont(new java.awt.Font("Garamond", 0, 14)); // NOI18N
        timeOut.setText("Time Out");
        timeOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                timeOutActionPerformed(evt);
            }
        });
        getContentPane().add(timeOut);
        timeOut.setBounds(160, 160, 90, 40);

        jLabel5.setFont(new java.awt.Font("Garamond", 1, 18)); // NOI18N
        jLabel5.setText("Users Timed In");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(90, 280, 130, 30);

        userlist.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { " " };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        userlist.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                userlistMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(userlist);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(90, 310, 120, 200);

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jScrollPane2.setFocusable(false);
        jScrollPane2.setRequestFocusEnabled(false);
        jScrollPane2.setWheelScrollingEnabled(false);

        message.setColumns(20);
        message.setEditable(false);
        message.setLineWrap(true);
        message.setRows(5);
        message.setFocusable(false);
        jScrollPane2.setViewportView(message);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(50, 210, 200, 60);

        jLabel6.setFont(new java.awt.Font("Garamond", 0, 16)); // NOI18N
        jLabel6.setText("ID Number :");
        getContentPane().add(jLabel6);
        jLabel6.setBounds(30, 120, 90, 30);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/MLFbgWhite1.jpg"))); // NOI18N
        getContentPane().add(jLabel1);
        jLabel1.setBounds(0, 0, 310, 530);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void idnumberfieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idnumberfieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_idnumberfieldActionPerformed

/* Updates a listModel that contains a list of the members currently timed in.
     * 
     * Return type: void
     */
    private void refreshListTimedIn(ResultSet rs) {
        DefaultListModel listModel = new DefaultListModel();
        
        try {
            while (rs.next()) {
                listModel.addElement(rs.getString("member_IDnumber"));
            }
        } catch (Exception e) {
            System.err.println(e);
        }
        
        userlist.setModel(listModel);
    }

    private void timeInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_timeInActionPerformed
        //check if id number field is null
        if(idnumberfield.getText().isEmpty())
            JOptionPane.showMessageDialog(null, "Please input ID number");
        else
        {
            Objects.Member mem = new Objects.Member();
            DBM.DBManager dbm = new DBM.DBManager();

            mem.setIdNo(idnumberfield.getText());
            if (mem.isLoggedInResidency()) {
                message.setText("You are alread timed in. ("
                        + idnumberfield.getText() + ")");
            }
            else {
                if (mem.timeIn()) {
                    message.setText("You have successfully timed in. ("
                            + idnumberfield.getText() + ")");
                    refreshListTimedIn(dbm.getLoggedInMembersList());
                    idnumberfield.setText("");
                }
                else {
                    message.setText("You could not be timed in to the residency "
                            + "system. Please contact the Documentations Manager to "
                            + "address the problem.");
                }
            }
        }
        
    }//GEN-LAST:event_timeInActionPerformed

    private void timeOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_timeOutActionPerformed
        // TODO add your handling code here:
        
        //check if has selected value in userlist
        if(idnumberfield.getText() == null)
            JOptionPane.showMessageDialog(null, "Please input ID number");
        else
        {
            Objects.Member mem = new Objects.Member();
            DBM.DBManager dbm = new DBM.DBManager();

            mem.setIdNo(idnumberfield.getText());
            if (mem.isLoggedInResidency()) {
                if (mem.timeOut()) {
                    // display: "You have successfully timed out"
                    message.setText("You have successfully timed out. ("
                            + idnumberfield.getText() + ")");
                    refreshListTimedIn(dbm.getLoggedInMembersList());
                    idnumberfield.setText("");
                }
            }
            else {
                message.setText("You have not yet timed in.");
            }
        }
    }//GEN-LAST:event_timeOutActionPerformed

    private void userlistMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_userlistMouseClicked
        if (userlist.getSelectedValue() != null) {
            idnumberfield.setText(userlist.getSelectedValue().toString());
        }
    }//GEN-LAST:event_userlistMouseClicked

    //prompt before exiting residency
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            ResultSet rs = new DBM.DBManager().getLoggedInMembersList();

            if (rs.next()) {
                JOptionPane.showMessageDialog(null, "There are still staffers timed in. "
                        + "Everyone should time out to exit this program.");
            }
            else {
                if (JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?",
                        "EXIT", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                    System.exit(1);
            }
        } catch (Exception e) {
            System.err.println(e);
        }
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ResidencyPageFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ResidencyPageFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ResidencyPageFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ResidencyPageFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ResidencyPageFinal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField idnumberfield;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea message;
    private javax.swing.JButton timeIn;
    private javax.swing.JButton timeOut;
    private javax.swing.JList userlist;
    // End of variables declaration//GEN-END:variables
}
